package com.itheima.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.entity.User;
import com.itheima.pojo.UserRequest;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import com.itheima.utils.ResultCode;
import com.itheima.utils.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;

    // 创建日志实例
    Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    /**
     * 1、查询全表
     * @return
     */

    public List<User> selectAll(){

        return userMapper.selectAll();
    }

    /**
     * 2、通过id查询
     * @return
     */
    public User selectid(UserRequest user) {
        Integer id = user.getId();
        logger.info("请求id:"+id);
        return userMapper.selectById(id);
    }

    /**
     * 3、通过id批量查询
     *      * @return
     */

    public List<User> selectlist(UserRequest userRe) {

        List<String> ids = userRe.getIds();
        return userMapper.selectBatchIds(ids);
    }

    /**
     * 4、注册
     * @return
     */

    public ResultVO register(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String phone = user.getPhone();
        //1.判断用户名，密码，手机号是否为空
        if (username != null && password != null && phone != null) {
            User users = userMapper.queryByUsername(username);
            if (users != null) {
                return ResultVO.error(ResultCode.USER_EXIST_ERROR.code,ResultCode.USER_EXIST_ERROR.msg);
            } else {
                String oldPassword = user.getPassword();
                // 获取颜值（随机生成一个颜值）
                String salt = UUID.randomUUID().toString().toUpperCase();
                // 将密码和颜值作为一个整体进行加密处理
                String md5Password = getMD5Password(oldPassword,salt);
                user.setPassword(md5Password);
                user.setSalt(salt);
                user.setIsDelete(0);
                user.setCreatedUser(user.getUsername());
                user.setModifiedUser(user.getUsername());
                Date date = new Date();
                user.setCreatedTime(date);
                user.setModifiedTime(date);
                return ResultVO.success(userService.save(user));
//                userMapper.insert(user)
            }
        } else {
            return ResultVO.error(ResultCode.USER_PASSWORD_ERROR.code,ResultCode.USER_PASSWORD_ERROR.msg);
        }

    }

    /**
     * 定义一个md5算法的加密处理
     */
    private String getMD5Password(String password,String salt){
        for (int i = 0; i < 3; i++) {
            // md5加密算法方法的调用（进行三次加密）
            password = DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();
        }
        return password;
    }


    /**
     * 5、登录
     *
     * @return
     */
    public ResultVO login(@RequestBody UserRequest use) {
        String username = use.getUsername();
        String password = use.getPassword();
        //1.判断用户名，密码是否为空
        if (username != null && password != null) {
            User users = userMapper.queryByUsername(username);
            //2.判断用户名是否存在
            if (users != null) {
                // 获取到数据库中的加密之后的密码
                String oldPassword = users.getPassword();
                // 获取在注册时所自动生成的颜值
                String salt = users.getSalt();
                // 将用户的密码按照相同的md5算法的规则进行加密
                String newMd5Password = getMD5Password(password,salt);

                //3.判断密码是否正确
                if (newMd5Password.equals(oldPassword)) {
                    // 4.密码正确，登录成功
                    return ResultVO.success(use.getUsername());
                } else {
                    return ResultVO.error(ResultCode.USER_ACCOUNT_ERROR.code,ResultCode.USER_ACCOUNT_ERROR.msg);
                }
            } else {
                return ResultVO.error(ResultCode.USER_NOT_EXIST.code,ResultCode.USER_NOT_EXIST.msg);
            }
        } else {
            return ResultVO.error(ResultCode.USER_PASSWORD_ERROR.code,ResultCode.USER_PASSWORD_ERROR.msg);
        }
    }


    /**
     * 根据id删除
     *
     * @return
     */
    public ResultVO deleteId(UserRequest user) {
        int id = user.getId();
        User use = userMapper.selectById(id);
        //1.判断用户id是否存在
        if (Objects.nonNull(use)) {
            Integer result = userMapper.deleteById(id);
            return ResultVO.success(result);
        }else {
            return ResultVO.error(ResultCode.USER_NOT_EXIST.code,ResultCode.USER_NOT_EXIST.msg);
        }
    }

    /**
     * 根据map集合删除
     *
     * @return
     */
//    public ResultVO deleteMap(@RequestBody User user) {
//        String username = user.getUsername();
//        int id = user.getId();
//
//        Map<String,Object> map = new HashMap<>();
//        map.put("username", username);
//        map.put("id", id);
//
//        Integer result = userMapper.deleteByMap(map);
//        return ResultVO.success(result);
//    }

    /**
     * 根据 数组 列表 删除
     *
     * @return
     */
    public Integer deletelist(UserRequest user) {


        List<String> ids = user.getIds();
        return userMapper.deleteBatchIds(ids);

    }


    /**
     * 修改
     *
     * @return
     */
    public ResultVO update(@RequestBody User user) {
        int id = user.getId();
        User use = userMapper.selectById(id);
        if (Objects.nonNull(use)) {
            Integer result = userMapper.updateById(user);
            return ResultVO.success(result);
        }
        return ResultVO.error("-1", "当前用户不存在,更新失败!");
    }


}